package com.maxmlr.music.util;

import com.maxmlr.music.constant.SystemConstant;
import com.maxmlr.music.model.Message;
import com.maxmlr.music.model.User;
import org.apache.commons.io.FileUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.*;



/**
 * 工具类
 * 
 * @author maxiao
 * 
 */
public class Tool implements SystemConstant {

	/**
	 * 取随机名称或id
	 * 
	 * @return
	 */
	public static String getRandomName() {
		String randomName = UUID.randomUUID().toString();
		return randomName;
	}

	/**
	 * 密码验证
	 * 
	 * @param pwd
	 *            密码
	 * @param encryptPwd
	 *            加密密码
	 * @return
	 */
	public static boolean comparePwd(String pwd, String encryptPwd) {
		if (encryptPwd.equals(Md5Util.md5(pwd))) {
			return true;
		}
		return false;
	}

	/**
	 * 空值判断，为null时，返回"";
	 * 
	 * @param obj
	 * @return
	 */
	public static String dellNull(Object obj) {
		String str = "";
		if (obj == null) {
			return str;
		}
		return obj.toString();
	}

	/**
	 * 空值判断，为null时，返回"";
	 * 
	 * @param obj
	 * @return
	 */
	public static Integer parseInt(Object obj) {
		Integer in = 0;
		String str = dellNull(obj);
		if ("".equals(str)) {
			return in;
		}
		try {
			in = Integer.parseInt(str);
		} catch (Exception e) {
			return 0;
		}
		return in;
	}

	/**
	 * 空值判断，为null时，返回0;
	 * 
	 * @param obj
	 * @return
	 */
	public static Long parseLong(Object obj) {
		Long in = (long) 0;
		String str = dellNull(obj);
		if ("".equals(str)) {
			return in;
		}
		try {
			in = Long.parseLong(str);
		} catch (Exception e) {
			return (long) 0;
		}
		return in;
	}

	/**
	 * 空值判断，为null时，返回0;
	 * 
	 * @param obj
	 * @return
	 */
	public static Double parseDouble(Object obj) {
		Double in = (double) 0;
		String str = dellNull(obj);
		if ("".equals(str)) {
			return in;
		}
		try {
			in = Double.parseDouble(str);
		} catch (Exception e) {
			return (double) 0;
		}
		return in;
	}

	/**
	 * 获取当前系统时间
	 * 
	 * @return
	 */
	public static Timestamp getNewtime() {
		return new Timestamp(System.currentTimeMillis());
	}

	/**
	 * 获取当前系统时间
	 * 
	 * @return
	 */
	public static Long getNewLongtime() {
		return System.currentTimeMillis();
	}

	/**
	 * 获取当前用户IP
	 * 
	 * @return
	 */
	public static String getRemoteHost() {
		return getHttpServletRequest().getRemoteHost();
	}

	/**
	 * 
	 * @return
	 */
	public static HttpServletRequest getHttpServletRequest() {
		// 获取request
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = attr.getRequest();
		return request;
	}

	/**
	 * 
	 * @return
	 */
	public static HttpSession getHttpSession() {
		return getHttpServletRequest().getSession();
	}

	/**
	 * 
	 * @return
	 */
	public static ServletContext getServletContext() {
		return getHttpSession().getServletContext();
	}

	/**
	 * 根据文件名加载配制文件
	 * 
	 * @param file
	 *            文件名
	 * @return
	 */
	public static Properties getProperties(String file) {
		Properties props = new Properties();
		try {
			ClassLoader classLoader = Tool.class.getClassLoader();
			InputStream is = classLoader.getResourceAsStream(file);
			props.load(is);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("加载properites文件错误");
		}
		return props;
	}

	/**
	 * 根据key 获取配制file文件中value值，没有匹配的返回本身
	 * 
	 * @param file
	 *            文件名
	 * @param key
	 * @return
	 */
	public static String getPropBykey(String file, String key) {
		String value = "";
		Properties prop = getProperties(file);
		value = prop.getProperty(key);
		if ("".equals(value) || value == null) {
			value = key;
		}
		return value;
	}

	/**
	 * 根据key 获取配制默认（tool.properties）文件中value值，没有匹配的返回本身,
	 * 
	 * @param key
	 * @return
	 */
	public static String getPropBykey(String key) {
		String value = "";
		Properties prop = getProperties("tool.properties");
		value = prop.getProperty(key);
		if ("".equals(value) || value == null) {
			value = key;
		}
		return value;
	}

	/**
	 * 按字节截取字符串
	 * 
	 * @param string
	 *            字符串
	 * @param begin
	 *            起始字节位数
	 * @param end
	 *            终止字节位数
	 * @return
	 */
	public static String subStringByByte(String str, int begin, int end) {
		String beginstr = subStringByByte(str, begin);
		String result = str.substring(beginstr.length() - 1);
		result = subStringByByte(result, end - begin);
		return result;
	}

	/**
	 * 按字节截取字符串
	 * 
	 * @param str
	 *            字符串
	 * @param len
	 *            截取长度
	 * @return
	 */
	public static String subStringByByte(String str, int len) {
		String result = null;
		if (str != null) {
			byte[] a = str.getBytes();
			if (a.length <= len) {
				result = str;
			} else if (len > 0) {
				result = new String(a, 0, len);
				int length = result.length();
				if (str.charAt(length - 1) != result.charAt(length - 1)) {
					if (length < 2) {
						result = null;
					} else {
						result = result.substring(0, length - 1);
					}
				}
				String next = str.substring(result.length() - 1,
						result.length());
				if (!next.equals(getPropBykey("unicode.properties", next))) {
					result += next;
				}
			}
		}
		return result;
	}

	/**
	 * 按指定字节长度截取字符串，返回list集合
	 * 
	 * @param str
	 * @param len
	 *            长度
	 * @return
	 */
	public static List<String> subStringByte(String str, int len) {
		List<String> list = new ArrayList<String>();
		if (str != null) {
			while (str.getBytes().length > len) {
				String result = subStringByByte(str, len);
				list.add(result);
				str = str.substring(result.length());
			}
			list.add(str);
		}
		return list;
	}

	/**
	 * 
	 * @param targetString
	 * @param byteIndex
	 * @return
	 * @throws Exception
	 */
	public static String getSubString(String targetString, int byteIndex)
			throws Exception {
		if (targetString.getBytes("UTF-8").length < byteIndex) {
			throw new Exception("超过长度");
		}
		String temp = targetString;
		for (int i = 0; i < targetString.length(); i++) {
			if (temp.getBytes("UTF-8").length <= byteIndex) {
				break;
			}
			temp = temp.substring(0, temp.length() - 1);
		}
		return temp;
	}

	/**
	 * 
	 * @param user
	 * @throws Exception
	 */
	public static void sendMessage(User user) throws Exception {
		String from = "18773334366@126.com";// 发件人
		String password = "cniavj1108";// 发件人密码
		String to = user.getEmail();// "752159277@qq.com";//收件人
		String subject = "爱音乐网站";// 主题
		String messageText = "尊敬的用户由于您最近的评论被检查为不良信息，管理员对您的密码进行了重设您的新密码为:["
				+ user.getPassword() + "],感谢您对爱我音乐网的支持谢谢!";// 内容
		Message mess = new Message();
		mess.setFrom(from);
		mess.setMessageText(messageText);
		mess.setPassword(password);
		mess.setSentDate(new Date());
		mess.setSubject(subject);
		mess.setTo(to);
		MessageUtil.message(mess);
	}

	/**
	 * 保存上传的文件
	 * 
	 * @param filename
	 *            保存的文件名
	 * @param dirfile
	 *            文件路径
	 * @param file
	 *            上传的文件
	 * @throws IOException
	 */
	public static void saveFile(String filename, String dirfile,
			MultipartFile file) throws IOException {
		String dir = getServletContext().getRealPath("/" + dirfile); // 设定文件保存的目录
		try {
			FileUtils.writeByteArrayToFile(new File(dir, filename),
					file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
			throw new IOException("文件写入失败！");
		}
	}

	/**
	 * 保存上传的文件
	 * 
	 * @param dirfile
	 *            文件路径
	 * @param file
	 *            上传的文件
	 * @throws IOException
	 */
	public static void saveFile(String dirfile, MultipartFile file)
			throws IOException {
		/**
		 * 取随机的文件名。
		 */
		String filename = Tool.getRandomName() + "." + dirfile;
		saveFile(filename, dirfile, file);
	}

}
